package com.lmh.backend.controller;

import com.lmh.backend.entity.User;
import com.lmh.backend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

@Controller
@RequestMapping(value = "/user")
public class UserController {
    private UserService userService;
    @Autowired
    private void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public ModelAndView sayHi() {
        ModelAndView mv = new ModelAndView("helloReader", "user", new User());
        mv.addObject("message", "Hello spring-mvc");
        return mv;
    }
    @RequestMapping(value = "/hello", method = RequestMethod.POST)
    public String login(User user, HttpServletRequest request,
                        HttpServletResponse response, RedirectAttributes attributes) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 查找有无此用户
        String username = user.getUsername();
        User realUser = userService.getUserByName(username);
        // 没有则返回登录界面并提示错误信息
        if(realUser == null) {
            attributes.addAttribute("notMatchError", "用户名不存在");
            return "redirect:hello";
        }
        // 有则检验密码是否匹配
        if(!realUser.getPassword().equals(user.getPassword())) {
            attributes.addAttribute("notMatchError", "用户名或密码错误");
            return "redirect:hello";
        }
        // 然后将用户名存入cookie
        Cookie cookie = new Cookie("username", user.getUsername());
        cookie.setMaxAge(60 * 60 * 24);
        cookie.setPath("/");
        response.addCookie(cookie);
        // session存储
        request.getSession().setAttribute("role", "USER");
        // 最后重定向到主页
        return "redirect:/news/home";
    }
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public ModelAndView register_form() {
        ModelAndView mv = new ModelAndView("register", "user", new User());
        return mv;
    }
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(User user, HttpServletRequest request, HttpServletResponse response,
                           RedirectAttributes attributes) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 进行注册
        // 检查两次密码输入是否一致
        String password = request.getParameter("password");
        String valid = request.getParameter("valid");
        // 不一致则返回注册界面并提示错误信息
        if(!password.equals(valid)) {
            attributes.addAttribute("passwordError", "两次密码输入不一致");
            return "redirect:register";
        }
        // 查找数据库中有无重复用户名
        String username = request.getParameter("username");
        // 有重复用户名则返回注册界面并提示错误信息
        User existUser = userService.getUserByName(username);
        // 无重复用户名则将用户数据存入数据库
        if(existUser != null) {
            attributes.addAttribute("usernameError", "用户已存在");
            return "redirect:register";
        }
        userService.save(user);
        // 注册成功后将username存入cookie
        Cookie cookie = new Cookie("username", username);
        cookie.setMaxAge(60 * 60 * 24);
        cookie.setPath("/");
        response.addCookie(cookie);
        // session存储
        request.getSession().setAttribute("role", "USER");
        // 重定向到首页
        return "redirect:/news/home";
    }
    @RequestMapping(value = "/exit", method = RequestMethod.GET)
    public String exit(HttpServletResponse response) {
        // 删除cookie
        Cookie cookie = new Cookie("username", null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        return "redirect:hello";
    }
}
